/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-01-01 15:27:15
 */

import { MenuItem } from '@/components/user/interface'
import { ContactsFriends, User } from '@/interface'
import { ChatUserGroup } from '@/interface/user'
import { BasicDataModule } from '@/store/modules/basicData'
import { errorTips } from '@/utils'
import pinyin from 'js-pinyin'
import { clone, equals, isEmpty } from 'ramda'

export interface UserInfoState {
	userInfo?: User
	groupChatInfo?: ChatUserGroup
	loading: boolean
	menu: MenuItem[]
}
export enum SearchType {
	userSearch = 'UserSearch',
	contactsSearch = 'ContactsSearch',
	userFilter = 'UserFilter',
}
export interface BuiltInUserMenuItem {
	title: string
	backgroundColor: string
	isActive: boolean
	icon: object
}
export interface BuiltInUserMenu {
	letter: string
	menu: BuiltInUserMenuItem[]
}
export interface PySegSort {
	letter: string
	data: ContactsFriends[]
}
export function pySegSort(arr: ContactsFriends[]): PySegSort[] {
	pinyin.setOptions({ checkPolyphone: false, charCase: 0 })
	const curr: PySegSort[] = [{ letter: '#', data: [] }]
	arr.forEach((data) => {
		let fristName = pinyin
			.getCamelChars(data.remarks ?? data.friendsName ?? data.groupChat.groupChatName)
			.substring(0, 1)
			.toUpperCase()
		if (equals(data.classType, 2)) {
			fristName = '群聊'
		}
		if (lettersArr.includes(fristName)) {
			const index = curr.findIndex((item) => equals(item.letter, fristName))
			if (equals(index, -1)) {
				curr.push({
					letter: fristName,
					data: [clone(data)],
				})
			} else {
				curr[index].data.push(data)
			}
		} else {
			curr[0].data.push(data)
		}
	})
	return curr
		.filter((item) => !isEmpty(item.data))
		.sort((x, y) => lettersArr.indexOf(x.letter) - lettersArr.indexOf(y.letter))
}

export const lettersArr = [
	'群聊',
	'A',
	'B',
	'C',
	'D',
	'E',
	'F',
	'G',
	'H',
	'I',
	'J',
	'K',
	'L',
	'M',
	'N',
	'O',
	'P',
	'Q',
	'R',
	'S',
	'T',
	'U',
	'V',
	'W',
	'X',
	'Y',
	'Z',
	'#',
]
// 发消息并添加聊天历史记录
export async function onSendMessage(historicalUserSessionsId: string): Promise<boolean> {
	const userId = localStorage.getItem('userId') as string
	const { success, msg } = await API.blog.historySession.createHistorySession.request({
		userId,
		historicalUserSessionsId: historicalUserSessionsId,
	})
	if (!success) {
		errorTips(msg)
	}
	BasicDataModule.getHistorySession()
	return success
}
